package cn.leyaber.hrm;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

//资源服务配置
@Configuration
@EnableResourceServer   //开启资源服务配置
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启方法授权
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    //配置资源id ,跟AuthorizationServerConfig.configure配置的resourceIds一样
    public static final String RESOURCE_ID = "hrm";

    //令牌签名的秘钥
    private static final String signKey = "123";

    //jwt的令牌转换器
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(signKey);
        return jwtAccessTokenConverter;
    }

    //token的存储方案
    @Bean
    public TokenStore tokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    //资源服务配置
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)
                .tokenStore(tokenStore());
    }

    //web安全配置
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            //校验scope必须为all ， 对应认证服务的客户端详情配置的clientId
            .antMatchers("/**").access("#oauth2.hasScope('all')")
            //关闭跨域伪造检查
            .and().csrf().disable()
            //把session设置为无状态，意思是使用了token，那么session不再做数据的记录
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
